﻿var reDate = /^((\d{1,2})\/(\d{1,2})\/(\d{4}))$/;//只做了格式验证
var rePassword = /^.{5,}$/;
var reAccount = /^[\w]{4,}$/;
var reEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;

function validateEmail(email) {
    if (!reEmail.test(email) && email != "") {
        top.Dialog.alert(email + "格式错误！");
        return false;
    }
    return true;
}

//日期时间正则
var reDateTime = /^\d{4}[/]([0][1-9]|(1[0-2]))[/]([1-9]|([012]\d)|(3[01]))([ \t\n\x0B\f\r])(([0-1]{1}[0-9]{1})|([2]{1}[0-4]{1}))([:])(([0-5]{1}[0-9]{1}|[6]{1}[0]{1}))([:])((([0-5]{1}[0-9]{1}|[6]{1}[0]{1})))$/;
var time = /([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))/;
function validateDateTime(datetime) {

    if (!reDateTime.test(datetime) && datetime != "") {
        jalert(R("Common_ValidateDateTime_Alert"));
        return false;
    }
    return true;
}

function validateDate(date) {

    if (!reDate.test(date) && date != "") {
        jalert(R("Common_ValidateDate_Alert", "输入日期格式不正确"));
        return false;
    }
    return true;
}

function validateStartDateEndDate(startDate, endDate) {

    if ((!time.test(startDate) && startDate != "") || (!time.test(endDate) && endDate != "")) {
        jalert(R("Common_ValidateDate_Alert", "输入日期格式不正确"));
        return false;
    }
    if (startDate != "" && endDate != "") {

        var startDate_arr = startDate.split("-");
        var startDate_date = new Date(startDate_arr[0], startDate_arr[1], startDate_arr[2]);
        var startDate_time = startDate_date.getTime();

        var endDate_arr = endDate.split("-");
        var endDate_date = new Date(endDate_arr[0], endDate_arr[1], endDate_arr[2]);
        var endDate_time = endDate_date.getTime();
        if (startDate_time > endDate_time) {
            jalert(R("Common_ValidateDateRange_Alert", "结束日期必须大于或等于开始日期"));
            return false;
        }
        else {
            return true;
        }
    }
    return true;
}

function validatePassword(value, msg) {
    if (!rePassword.test(value)) {
        jalert(msg + R("Common_ValidatePassword_Alert", "密码必须大于6位，且只能为数字，字母，下划线组成"));
        return false;
    }
    return true;
}
function validateAccount(value, msg) {
    if (!reAccount.test(value)) {
        jalert(msg + R("Common_ValidateAccount_Alert", "必须大于5位，且只能为数字，字母，下划线组成"));
        return false;
    }
    return true;
}

function loading() {
    $("<div class=\"datagrid-mask\"></div>").css({ display: "block", width: "100%", height: $(window).height() }).appendTo("body");
    $("<div class=\"datagrid-mask-msg\"></div>").html(R("Common_Loading_Tip", "Loading...")).appendTo("body").css({ display: "block", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 });
}
function dispalyLoad() {
    $(".datagrid-mask").remove();
    $(".datagrid-mask-msg").remove();
}

function tooltpis(value, row) {
    if (value != null)
        return "<span title='" + value + "'>" + value + "<span>";
}

function fmoney(s, n) {
    if (!s) return "0.00";
    var n = s, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "")
}

function fnumber(s) {
    return fmoney(s, 0);
}

function fTransPoint(s) {
    return fmoney(s, 1);
}

function fText(v) {
    return "<div class='ellipsis' style='width:300px' title=\"" + htmlEncode(v) + "\">" + v + "</div>";
}

function htmlEncode(str) {
    var s = "";
    if (!str || str.length == 0) return "";
    s = str.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    return s;
}

(function ($) {
    if (!$.setCookie) {
        $.extend({
            setCookie: function (c_name, value, exdays) {
                try {
                    if (!c_name) return false;
                    var exdate = new Date();
                    exdate.setDate(exdate.getDate() + exdays);
                    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
                    document.cookie = c_name + "=" + c_value;
                    //document.cookie = c_name + "=" + c_value + ";domain=localhost:2259";
                    //document.domain = "wwwcomy.com";
                }
                catch (err) {
                    return '';
                };
                return '';
            }
        });
    };
    if (!$.getCookie) {
        $.extend({
            getCookie: function (c_name) {
                try {
                    var i, x, y,
                        ARRcookies = document.cookie.split(";");
                    for (i = 0; i < ARRcookies.length; i++) {
                        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                        x = x.replace(/^\s+|\s+$/g, "");
                        if (x == c_name) return (y);
                    };
                }
                catch (err) {
                    return '';
                };
                return '';
            }
        });
    };
})(jQuery);

function checkRequired() {
    $(".formtable th").append("<span class='red'>&nbsp;</span>");
    $(".formtable td").find(".required").parent().prev().find("span").html("*")
}

function fStatus(value) {
    switch (value) {
        case 1:
            return '<span class="label label-success">' + R("Status_Enable", "Enable") + "</span>";
            break;
        case 2:
            return '<span class="label label-danger">' + R("Status_Disable", "Disable") + "</span>";
            break;

    }
}
function logType(value) {
    switch (value) {
        case 1:
            return '<span class="label label-success">' + R("logType_Admin", "Admin", "管理员日志") + "</span>";
            break;
        default:
            return '<span class="label label-danger">' + R("logType_Member", "Member", "会员日志") + "</span>";
            break;

    }
}
function fSex(value) {
    switch (value) {
        case 1:
            return '<span class="label label-success">' + R("Sex_male", "male", "男") + "</span>";
            break;
        case 2:
            return '<span class="label label-danger">' + R("Status_Female", "Female", "女") + "</span>";
            break;
        default:
            return '<span class="">' + "未知" + "</span>";
            break;

    }
}
function fMoneyColor(v) {
    v = v * 1;
    return v == 0 ? v : (v < 0 ? "<span class='dn'>" + fmoney(v) + "</span>" : "<span class='up'>" + fmoney(v) + "</span>");
}
////0未激活，1正常，2不能登录，3不能操作资金
//function mStatus(value, row) {
//    switch (value) {
//        case 0:
//            return '<span class="label label-default">'+R("M_Common", "NotActivated", "未激活")+"</span>";
//            break;
//        case 1:
//            return '<span class="label label-primary">'+R("M_Common", "normal", "正常")+"</span>"; 
//            break;
//        case 2:
//            return '<span class="label label-success">'+R("M_Common", "nolog", "不能登录")+"</span>";
//            break;
//        case 3:
//            return  '<span class="label label-danger">'+R("M_Common", "Inoperablefunds", "不能操作资金")+"</span>"; 
//            break;
//    }
//}
function fYesNo(value) {
    if (value) return '<span class="label label-success">' + R("Status_Yes", "Yes") + "</span>";
    else return '<span class="label label-danger">' + R("Status_No", "No") + "</span>";
}
//留言状态
function LeaveStatus(value) {
    switch (value) {
        case 1:
            return "未处理";
        case 2:
            return "处理中";
        case 3:
            return "已解决";
        case 4:
            return "已完成";
    }
}
//资产类型
function AssetType(value) {
    switch (value) {
        case 'LastIncome':
            return R("LastIncome", "期初权益");
        case 'UsedMoney':
            return R("UsedMoney", "占用保证金");
        case 'FrozenMoney':
            return R("FrozenMoney", "冻结保证金");
        case 'FrozenFee':
            return R("FrozenFee", "冻结手续费");
        case 'TodayInMoney':
            return R("TodayInMoney", "当日入金");
        case 'TodayOutMoney':
            return R("TodayOutMoney", "当日出金");
        case 'TodayProfit':
            return R("TodayProfit", "当日盈亏");
        case 'TodayFee':
            return R("TodayFee", "当日手续费");
        case 'LastDelayFee':
            return R("LastDelayFee", "上日延期费");
        case 'FloatingProfit':
            return R("FloatingProfit", "浮动盈亏");
        case 'AvailableMoney':
            return R("AvailableMoney", "可用保证金");
        case 'CurrentIncome':
            return R("CurrentIncome", "当前权益");
        case 'MoneyRisk':
            return R("MoneyRisk", "资金风险率");
        case 'OpenContractProfit':
            return R("OpenContractProfit", "持仓盈亏");
        case 'TradeFeeAward':
            return R("TradeFeeAward", "交易佣金");
        default:
            return R("unknown", "未知");
    }
}
//资产变动类型
function ChangeType(value) {
    switch (value) {
        case 100:
            return R("Recharge", "充值");
        case 200:
            return R("withdraw", "提现");
        case 201:
            return R("WithdrawalsBy", "提现通过");
        case 202:
            return R("WithdrawNotPass", "提现不通过");
        case 203:
            return R("WithdrawRevocation", "提现撤销");
        case 300:
            return R("NewDelegate", "新增委托");
        case 301:
            return R("RevokesDelegation", "撤消委托");
        case 302:
            return R("OpenWarehouse", "建仓");
        case 303:
            return R("CloseWarehouse", "平仓");
        case 304:
            return R("Billing", "结算");
        default:
            return R("unknown", "未知");
    }
}
function jalert(msg) {
    $("#alert .modal-body p").html(msg);
    $("#alert").modal("show");
}

function jconfirm(msg, obj) {
    $("#confirm .modal-body p").html(msg);
    $("#confirm").modal("show");

    $("#confirm .btn-primary").one("click", function () {
        obj();
        $("#confirm").modal("hide");
    });
}

/*
//两种调用方式
var template1 = "我是{0}，今年{1}了";
var template2 = "我是{name}，今年{age}了";
var result1 = template1.format("loogn", 22);
var result2 = template2.format({ name: "loogn", age: 22 });
//两个结果都是"我是loogn，今年22了"
*/
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

function checkChar(InString) {
    var RefString = "<";
    var RefString2 = "%";
    var RefString3 = "\"";
    var RefString4 = ">";
    var RefString5 = "~";
    var RefString6 = "&";
    var RefString7 = "?";
    var RefString8 = "'";
    for (Count = 0; Count < InString.length; Count++) {
        TempChar = InString.substring(Count, Count + 1);
        if ((RefString.indexOf(TempChar, 0) == 0) || (RefString2.indexOf(TempChar, 0) == 0) || (RefString3.indexOf(TempChar, 0) == 0) || (RefString4.indexOf(TempChar, 0) == 0) || (RefString5.indexOf(TempChar, 0) == 0) || (RefString6.indexOf(TempChar, 0) == 0) || (RefString7.indexOf(TempChar, 0) == 0) || (RefString8.indexOf(TempChar, 0) == 0)) {
            return (false);
        }
    }
    return (true);
}

function ChangeToTable(printDatagrid) {

}

function Export(strXlsName, printDatagrid, exportUrl, urlParams) {
    var f = $('<form action="' + exportUrl + '" method="post" id="fmExport"></form>');
    var $content = $('<input type="hidden" id="txtContent" name="txtContent" />');
    var $name = $('<input type="hidden" id="txtName" name="txtName" />');

    var tableString = '[table cellspacing="0" class="pb"]';
    var options = printDatagrid.datagrid("options");
    var frozenColumns = options.frozenColumns;  // 得到frozenColumns对象
    var columns = options.columns;    // 得到columns对象
    var nameList = new Array();

    // 载入title
    if (typeof columns != 'undefined' && columns != '') {
        $(columns).each(function (index) {
            tableString += '\n[tr]';
            if (typeof frozenColumns != 'undefined' && typeof frozenColumns[index] != 'undefined') {
                for (var i = 0; i < frozenColumns[index].length; ++i) {
                    if (!frozenColumns[index][i].hidden) {
                        tableString += '\n[th width="' + frozenColumns[index][i].width + '"';
                        if (typeof frozenColumns[index][i].rowspan != 'undefined' && frozenColumns[index][i].rowspan > 1) {
                            tableString += ' rowspan="' + frozenColumns[index][i].rowspan + '"';
                        }
                        if (typeof frozenColumns[index][i].colspan != 'undefined' && frozenColumns[index][i].colspan > 1) {
                            tableString += ' colspan="' + frozenColumns[index][i].colspan + '"';
                        }
                        if (typeof frozenColumns[index][i].field != 'undefined' && frozenColumns[index][i].field != '') {
                            nameList.push(frozenColumns[index][i]);
                        }
                        tableString += ']' + frozenColumns[0][i].title + '[/th]';
                    }
                }
            }
            for (var i = 0; i < columns[index].length; ++i) {
                if (!columns[index][i].hidden) {
                    tableString += '\n[th width="' + columns[index][i].width + '"';
                    if (typeof columns[index][i].rowspan != 'undefined' && columns[index][i].rowspan > 1) {
                        tableString += ' rowspan="' + columns[index][i].rowspan + '"';
                    }
                    if (typeof columns[index][i].colspan != 'undefined' && columns[index][i].colspan > 1) {
                        tableString += ' colspan="' + columns[index][i].colspan + '"';
                    }
                    if (typeof columns[index][i].field != 'undefined' && columns[index][i].field != '') {
                        nameList.push(columns[index][i]);
                    }
                    tableString += ']' + columns[index][i].title + '[/th]';
                }
            }
            tableString += '\n[/tr]';
        });
    }

    var params = { page: 1, rows: 10000 };

    $.extend(params, urlParams);

    $.post(options.url, params, function (data) {
        // 载入内容
        var rows = data.rows == null ? data : data.rows; // 这段代码是获取当前页的所有行
        for (var i = 0; i < rows.length; ++i) {
            tableString += '\n[tr]';
            for (var j = 0; j < nameList.length; ++j) {
                var e = nameList[j].field.lastIndexOf('_0');
                tableString += '\n[td';
                if (nameList[j].align != 'undefined' && nameList[j].align != '') {
                    //tableString += ' style="text-align:' + nameList[j].align + ';"';
                }
                tableString += ']';
                var v = "";
                if (e + 2 == nameList[j].field.length) {
                    v = rows[i][nameList[j].field.substring(0, e)];
                }
                else
                    v = rows[i][nameList[j].field];

                if (nameList[j].formatter) {
                    tableString += nameList[j].formatter(v, rows[i]).replace(/\<([^\>]*)\>/gi, "[$1]");
                }
                else {
                    tableString += v == null ? "" : v;
                }

                tableString += '[/td]';
            }
            tableString += '\n[/tr]';
        }

        tableString += '\n[/table]';

        $content.val(tableString);
        $content.appendTo(f);
        $name.val(strXlsName);
        $name.appendTo(f);
        f.appendTo(document.body).submit();
        f.remove();

    }, "json");

}

function fileChange(target, id) {
    var ext = /\.[^\.]+$/.exec(document.getElementById(id).value)[0];
    var flags = false;
    for (var i = 0; i < arr2.length; i++) {
        if (arr2[i].toLowerCase() == ext.toLowerCase()) {
            flags = true;
        }
    }
    if (flags == false && document.getElementById(id).value != "") {
        jalert('图片的格式不对,只能上传：.png、.jpg、.jpeg格式的图片！');
        document.getElementById(id).value = "";
        return false;
    }
    if (document.getElementById(id).value == "") {
        return false;
    }
    //检测上传文件的大小        
    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
    var fileSize = 0;
    if (isIE && !target.files) {
        var filePath = target.value;
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
        var file = fileSystem.GetFile(filePath);
        fileSize = file.Size;
    } else {
        fileSize = target.files[0].size;
    }
    if (fileSize > (5 * 1024 * 1024)) {
        jalert('文件大小不能超过5MB,请重新选择图片！');
        document.getElementById(id).value = "";
        return false;
    }
}

var signalR = $.connection.TickerHub;
function initSignalR(callback) {
    $.connection.hub.start().done(function () {
        callback();
    });

    var tryingToReconnect = false;

    $.connection.hub.connectionSlow(function () {
        console.log("连接服务器的速度太慢.");
    });

    $.connection.hub.reconnecting(function () {
        tryingToReconnect = true;
        console.log("连接服务器中...");

    });

    $.connection.hub.reconnected(function () {
        tryingToReconnect = false;
        console.log("连接服务器成功.");

    });

    $.connection.hub.disconnected(function () {
        if (tryingToReconnect) {
            console.log("连接服务器失败.");

            setTimeout(function () {
                $.connection.hub.start();
            }, 5e3); // Restart connection after 5 seconds.
        }

        if ($.connection.hub.lastError) {
            console.log("Disconnected. Reason: " + $.connection.hub.lastError.message);

            setTimeout(function () {
                $.connection.hub.start();
            }, 5e3); // Restart connection after 5 seconds.
        }
    });
}


$(function () {
    checkRequired();

    // Disable search and ordering by default
    $.extend($.fn.dataTable.defaults, {
        "searching": false,
        "ordering": false,
        "lengthChange": false,
        "pageLength": 20,
        //"paging": false,
        "processing": true,
        "serverSide": true,
    });

    //add selected
    $('body').on('click', '#table tbody tr', function () {
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
        }
        else {
            $(this).siblings().removeClass('selected');
            $(this).addClass('selected');
        }
    });
});
